<?php
class ControllerSaleCheckMainStock extends Controller {
  private $error = array();

  public function vendor(){
    $this->load->model('sale/check_stock');
    $json = array();
    $filter_name = I('get.filter_name');
    if(!$filter_name){
      $filter_name='';
    }
    $vendors = $this->model_sale_check_stock->getVendors($filter_name);
    if($vendors){
      $json = $vendors;
    }

    $this->response->addHeader('Content-Type: application/json');
    $this->response->setOutput(json_encode($json));
  }

  public function product(){
    $json = array();

    if (isset($this->request->get['filter_name']) || isset($this->request->get['filter_model'])) {
      $this->load->model('catalog/product');
      $this->load->model('catalog/option');
      $this->load->model('sale/check_stock');

      

      if (isset($this->request->get['filter_name'])) {
        $filter['pd.name'] = array('like', '%'.$this->request->get['filter_name'].'%');
      }
      if(isset($this->request->get['filter_vendor'])){
        $filter['vendor.vendor'] = $this->request->get['filter_vendor'];
      }

      $results = $this->model_sale_check_stock->getProducts($filter);

      foreach ($results as $result) {
        $option_data = array();

        $product_options = $this->model_catalog_product->getProductOptions($result['product_id']);

        foreach ($product_options as $product_option) {
          $option_info = $this->model_catalog_option->getOption($product_option['option_id']);

          if ($option_info) {
            $product_option_value_data = array();

            foreach ($product_option['product_option_value'] as $product_option_value) {
              $option_value_info = $this->model_catalog_option->getOptionValue($product_option_value['option_value_id']);

              if ($option_value_info) {
                $product_option_value_data[] = array(
                  'product_option_value_id' => $product_option_value['product_option_value_id'],
                  'option_value_id'         => $product_option_value['option_value_id'],
                  'name'                    => $option_value_info['name'],
                  'price'                   => (float)$product_option_value['price'], 
                  'price_prefix'            => $product_option_value['price_prefix']
                );
              }
            }

            $option_data[] = array(
              'product_option_id'    => $product_option['product_option_id'],
              'product_option_value' => $product_option_value_data,
              'option_id'            => $product_option['option_id'],
              'name'                 => $option_info['name'],
              'type'                 => $option_info['type'],
              'value'                => $product_option['value'],
              'required'             => $product_option['required']
            );
          }
        }

        $json[] = array(
          'product_id' => $result['product_id'],
          'name'       => strip_tags(html_entity_decode($result['name'], ENT_QUOTES, 'UTF-8')),
          'model'      => $result['model'],
          'cost'          => $result['product_cost'],
          'sku'         =>$result['sku'],
          'option'     => $option_data,
          'price'      => $result['price']
        );
      }
    }

    $this->response->addHeader('Content-Type: application/json');
    $this->response->setOutput(json_encode($json));
  }
  // public function exportShipping(){
  //   $po_id = I('get.po_id');
  //   if(!$po_id){
  //     $po_id = 0;
  //   }
  //   $this->load->model('sale/check_stock');
  //   $po = $this->model_sale_check_stock->getPo($po_id);

  //   $data['po'] = $po;

  //   if(!$po){
  //     $this->load->language('error/not_found');
 
  //     $this->document->setTitle($this->language->get('heading_title'));

  //     $data['heading_title'] = $this->language->get('heading_title');
 
  //     $data['text_not_found'] = $this->language->get('text_not_found');
 
  //     $data['breadcrumbs'] = array();

  //     $data['breadcrumbs'][] = array(
  //       'text' => $this->language->get('heading_title'),
  //       'href' => $this->url->link('error/not_found', 'token=' . $this->session->data['token'], 'SSL')
  //     );
 

  //     $data['footer'] = $this->load->controller('common/footer');
 
  //     $this->response->setOutput($this->load->view('error/not_found.tpl', $data));
  //   }
  //   $po_products = $this->model_sale_check_stock->getRequisitionProducts($po_id);
  //   $count = 0;
  //   foreach ($po_products as $key => $po_product) {
  //     $count += $po_product['qty'];
  //   }

  //   $this->load->library('PHPExcel/PHPExcel');
  //   $objReader = PHPExcel_IOFactory::createReader('Excel5');
  //   $objPHPExcel = $objReader->load(DIR_SYSTEM . "template/order_shipping.xls"); 
  //   $objPHPExcel->getProperties()->setCreator("Think-tec")
  //              ->setLastModifiedBy("Think-tec")
  //              ->setTitle("Bai Huo Zhan PO")
  //              ->setSubject("Bai Huo Zhan PO")
  //              ->setDescription("Bai Huo Zhan PO")
  //              ->setKeywords("Bai Huo Zhan, Think-tec")
  //              ->setCategory("Think-tec");
  //   // $objPHPExcel->setActiveSheetIndex(0);
  //   $objActSheet = $objPHPExcel->getActiveSheet();
  //   $objPHPExcel->getActiveSheet()->getStyle('C1')->getFont()->setSize(48);
  //   $objActSheet->setCellValue('C1', $po['logcenter_info']['shipping_zone_city']);
  //   //$objPHPExcel->getActiveSheet()->getStyle('B2')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
  //   $objPHPExcel->getActiveSheet()->getStyle('B2')->getFont()->setSize(16);
  //   $objActSheet->setCellValue('B2', $po['included_order_ids']);
  //   $objPHPExcel->getActiveSheet()->getStyle('B3')->getFont()->setSize(16);
  //   $objActSheet->setCellValue('B3', $po['id']);
  //   $objPHPExcel->getActiveSheet()->getStyle('B5')->getFont()->setSize(16);
  //   $objActSheet->setCellValue('B5', $po['logcenter_info']['firstname']);
  //   $objActSheet->setCellValue('B6', $po['logcenter_info']['address_1']);
  //   $objActSheet->setCellValue('B7', $po['logcenter_info']['telephone']);

  //   //$objPHPExcel->getActiveSheet()->getStyle('A7:G'.$requisitionw_num)->getFont()->setSize(12);
    
  //   $objActSheet->setTitle('库存查看');


  //   $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
  //   ob_end_clean();
  //   // Redirect output to a client’s web browser (Excel2007)
  //   header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  //   header('Content-Disposition: attachment;filename="PO_BHZ_'.date('Y-m-d-H-i',time()).'.xlsx"');
  //   header('Cache-Control: max-age=0');
  //   // If you're serving to IE 9, then the following may be needed
  //   header('Cache-Control: max-age=1');
  //   // If you're serving to IE over SSL, then the following may be needed
  //   header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
  //   header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
  //   header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
  //   header ('Pragma: public'); // HTTP/1.0
  //   $objWriter->save('php://output'); 
  //   exit;
  // }
  // public function export(){
  //   $po_id = I('get.po_id');
  //   if(!$po_id){
  //     $po_id = 0;
  //   }
  //   $this->load->model('sale/check_stock');
  //   $po = $this->model_sale_check_stock->getPo($po_id);
  //   $data['po'] = $po;
  //   if(!$po){
  //     $this->load->language('error/not_found');
 
  //     $this->document->setTitle($this->language->get('heading_title'));

  //     $data['heading_title'] = $this->language->get('heading_title');
 
  //     $data['text_not_found'] = $this->language->get('text_not_found');
 
  //     $data['breadcrumbs'] = array();

  //     $data['breadcrumbs'][] = array(
  //       'text' => $this->language->get('heading_title'),
  //       'href' => $this->url->link('error/not_found', 'token=' . $this->session->data['token'], 'SSL')
  //     );
 

  //     $data['footer'] = $this->load->controller('common/footer');
 
  //     $this->response->setOutput($this->load->view('error/not_found.tpl', $data));
  //   }
  //   $po_products = $this->model_sale_check_stock->getRequisitionProducts($po_id);
  //   $data['po_products'] = $po_products;

  //   $this->load->library('PHPExcel/PHPExcel');
  //   $objReader = PHPExcel_IOFactory::createReader('Excel5');
  //   $objPHPExcel = $objReader->load(DIR_SYSTEM . "template/po_tpl.xls"); 
  //   $objPHPExcel->getProperties()->setCreator("Think-tec")
  //              ->setLastModifiedBy("Think-tec")
  //              ->setTitle("Bai Huo Zhan PO")
  //              ->setSubject("Bai Huo Zhan PO")
  //              ->setDescription("Bai Huo Zhan PO")
  //              ->setKeywords("Bai Huo Zhan, Think-tec")
  //              ->setCategory("Think-tec");
  //   // $objPHPExcel->setActiveSheetIndex(0);
  //   $objActSheet = $objPHPExcel->getActiveSheet();
  //   $objActSheet->setCellValue('B2', $po['id']);
  //   $objPHPExcel->getActiveSheet()->getStyle('B2')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
  //   $objActSheet->setCellValue('F2', date('Y-m-d H:i',time()));
  //   $objActSheet->setCellValue('B3', $po['vendor_id']);
  //   $objActSheet->setCellValue('B4', $po['vendor']['vendor_name']);
  //   $objActSheet->setCellValue('F3', $po['vendor']['firstname']);
  //   $objActSheet->setCellValue('F4', $po['vendor']['telephone']);

  //   $requisitionw_num = 6;
  //   $styleBorderOutline = array(
  //     'borders' => array(
  //       'outline' => array(
  //         'style' => PHPExcel_Style_Border::BORDER_THIN,
  //       ),
  //     ),
  //   );
  //   $objPHPExcel->getActiveSheet()->insertNewRowBefore(7, count($po_products));
  //   $count = 0;
  //   foreach ($po_products as $key => $po_product) {
  //     $requisitionw_num++;
  //     $objActSheet->setCellValue('A'.$requisitionw_num, $requisitionw_num-6);
  //     $objActSheet->setCellValue('B'.$requisitionw_num, $po_product['name'].' '.$po_product['option_name']);
  //     $objActSheet->setCellValue('C'.$requisitionw_num, $po_product['sku']);
  //     $objActSheet->setCellValue('D'.$requisitionw_num, $po_product['qty']);
  //     $objActSheet->setCellValue('E'.$requisitionw_num, $po_product['unit_price']);
  //     $objActSheet->setCellValue('F'.$requisitionw_num, $po_product['price']);
  //     $objActSheet->setCellValue('G'.$requisitionw_num, $po_product['comment']);

  //     $count += $po_product['qty'];

  //     $objPHPExcel->getActiveSheet()->getStyle('A'.$requisitionw_num)->applyFromArray($styleBorderOutline);
  //     $objPHPExcel->getActiveSheet()->getStyle('B'.$requisitionw_num)->applyFromArray($styleBorderOutline);
  //     $objPHPExcel->getActiveSheet()->getStyle('C'.$requisitionw_num)->applyFromArray($styleBorderOutline);
  //     $objPHPExcel->getActiveSheet()->getStyle('D'.$requisitionw_num)->applyFromArray($styleBorderOutline);
  //     $objPHPExcel->getActiveSheet()->getStyle('E'.$requisitionw_num)->applyFromArray($styleBorderOutline);
  //     $objPHPExcel->getActiveSheet()->getStyle('F'.$requisitionw_num)->applyFromArray($styleBorderOutline);
  //     $objPHPExcel->getActiveSheet()->getStyle('G'.$requisitionw_num)->applyFromArray($styleBorderOutline);
  //   }
  //   $requisitionw_num++;

  //   $objActSheet->setCellValue('D'.$requisitionw_num, $count);
  //   $objActSheet->setCellValue('F'.$requisitionw_num, $po['total']);
  //   $requisitionw_num++;
  //   $objActSheet->setCellValue('F'.$requisitionw_num, date('Y-m-d', strtotime($po['deliver_time'])));

  //   $objPHPExcel->getActiveSheet()->getStyle('A7:G'.$requisitionw_num)->getFont()->setSize(16);
    
  //   $objActSheet->setTitle('库存查看');


  //   $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
  //   ob_end_clean();
  //   // Redirect output to a client’s web browser (Excel2007)
  //   header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  //   header('Content-Disposition: attachment;filename="PO_BHZ_'.date('Y-m-d-H-i',time()).'.xlsx"');
  //   header('Cache-Control: max-age=0');
  //   // If you're serving to IE 9, then the following may be needed
  //   header('Cache-Control: max-age=1');
  //   // If you're serving to IE over SSL, then the following may be needed
  //   header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
  //   header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
  //   header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
  //   header ('Pragma: public'); // HTTP/1.0
  //   $objWriter->save('php://output'); 
  //   exit;
  // }

  public function index() {

    $this->document->setTitle('库存查看');

    $this->load->model('sale/check_stock');

    $this->getList();
  }

  public function add() {
    $this->document->setTitle('新增库存查看');
    $this->document->addScript('view/javascript/angular.js');
    $this->document->addScript('view/javascript/bhz_ctl.js');

    $this->load->model('sale/check_stock');

    $this->form();
  }

  public function view(){

    $this->document->setTitle('查看库存查看');

    $this->document->addScript('view/javascript/angular.js');
    $this->document->addScript('view/javascript/bhz_ctl.js');

    $this->load->model('sale/check_stock');
    $data['breadcrumbs'] = array();

    $data['breadcrumbs'][] = array(
      'text' => $this->language->get('text_home'),
      'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
    );

    $data['breadcrumbs'][] = array(
      'text' => '库存查看',
      'href' => $this->url->link('sale/check_main_stock', 'token=' . $this->session->data['token'] , 'SSL')
    );

    $data['token'] = $this->session->data['token'];

    if($this->user->getLp()){
      $where['requisition.src_logcenter'] = $this->user->getLp();
      $where['requisition.des_logcenter'] = $this->user->getLp();
      $where['_logic'] = 'or';
      $filter['_complex'] = $where;
    }

    $data = I('get.');

    

    if(isset($data['filter_date_end'])){
      if($this->validateDate($data['filter_date_end'],'Y-m-d')){
        $filter_date_end = $data['filter_date_end'];
      }else{
        $filter_date_end = '9999-12-31';
      } 
    }else{
      $filter_date_end = '9999-12-31';
    }

    $filter['filter_date_end'] = $filter_date_end;

    if(isset($data['filter_vendor_name'])){
      $filter_vendor_name = trim($data['filter_vendor_name']);
    }else{
      $filter_vendor_name = '';
    }

    $filter['filter_vendor_name'] = $filter_vendor_name;

    if(!empty($data['filter_logcenter'])){
      $filter_logcenter = trim($data['filter_logcenter']);
    }else{
      $filter_logcenter = 4;
    }

    if(isset($data['filter_date_start'])){

      if($this->validateDate($data['filter_date_start'],'Y-m-d')){
        $filter_date_start = $data['filter_date_start'];
      }else{
        $filter_date_start = $this->getStartTime($filter_logcenter);
      }   
    }else{
      $filter_date_start = $this->getStartTime($filter_logcenter);
    }

    $filter['filter_date_start'] = $filter_date_start;

    $filter['filter_logcenter'] = $filter_logcenter;

    if(!empty($data['filter_sku'])){
      $filter_sku = trim($data['filter_sku']);
    }else{
      $filter_sku = '';
    }

    $filter['filter_sku'] = $filter_sku;

    if (isset($this->session->data['error'])) {
      $data['error_warning'] = $this->session->data['error'];

      unset($this->session->data['error']);
    } elseif (isset($this->error['warning'])) {
      $data['error_warning'] = $this->error['warning'];
    } else {
      $data['error_warning'] = '';
    }

    if (isset($this->session->data['success'])) {
      $data['success'] = $this->session->data['success'];

      unset($this->session->data['success']);
    } else {
      $data['success'] = '';
    }


    $check_stock = $this->model_sale_check_stock->getOptionProductsByProductId($filter);
    $data['check_stock'] = $check_stock;
    $data['export_url'] = URL('sale/check_main_stock/export', 'token='.$data['token'].'&sku='.$filter_sku.'&filter_date_start'.$data['filter_date_start'].'&filter_date_end'.$data['filter_date_end'].'&filter_logcenter='.$data['filter_logcenter']);
    $data['header'] = $this->load->controller('common/header');
    $data['column_left'] = $this->load->controller('common/column_left');
    $data['footer'] = $this->load->controller('common/footer');

    $this->response->setOutput($this->load->view('sale/check_main_stock_view.tpl', $data));
  }

  public function save(){
    if ($this->request->server['REQUEST_METHOD'] == 'POST') {
      $this->load->model('sale/check_stock');
      $data = json_decode(file_get_contents('php://input'), true);

      $filter = C('DEFAULT_FILTER');
      $data   =   is_array($data) ? array_map_recursive($filter,$data) : $filter($data);

      if(!$data['deliver_time'] || !$data['products']||!$data['vendor']||!$data['logcenter']){

        $this->response->setOutput(json_encode(array('success'=>false, 'info'=>'数据不完整')));
      }
      else{
        $requisition_id = $this->model_sale_check_stock->addRequisition($data, $this->user->getId());
      }
      $this->response->setOutput(json_encode(array('success'=>true, 'info'=>$requisition_id)));
      return;
    }
  }

  public function confirmStock(){
    if ($this->request->server['REQUEST_METHOD'] == 'POST') {
      $this->load->model('sale/check_stock');
      $data = json_decode(file_get_contents('php://input'), true);
      $filter = C('DEFAULT_FILTER');
      $data   =   is_array($data) ? array_map_recursive($filter,$data) : $filter($data);

      // $id = I('post.po_id');
      $id = $data['requisition_id'];
      if(!$id){
        $id=0;
      }
      $requisition = $this->model_sale_check_stock->getRequisition($id);
      //判断po状态，如果是已经结算或者已经关闭，
      if($requisition['status'] != 2 ) {
        $this->response->setOutput(json_encode(array('error'=>'不能修改库存查看')));

      }  

        $this->model_sale_check_stock->changeRequisitionStatus($id, 3);
        //确认库存查看 
       
        $comment = '后台确认库存查看';

        $this->model_sale_check_stock->addRequisitionHistory($id, $this->user->getId(), $this->user->getUserName(), $comment);  
  

      $this->response->setOutput(json_encode(array('success'=>'后台成功确认库存查看')));
      return;
    } 
  }

  public function delete() {
    $json = array();

    $this->load->model('sale/check_stock');

    $id = I('get.requisition_id');
    if(!$id){
      $id=0;
    }

    $requisition = $this->model_sale_check_stock->getRequisition($id);
    if(!$requisition||$requisition['status']!=1) {
      $json['error'] = '非新增状态库存查看不能删除';
    }
    else {
      $this->model_sale_check_stock->deleteRequisition($id);
      $json['success'] = '删除成功';
    }

    if (isset($this->request->server['HTTP_ORIGIN'])) {
      $this->response->addHeader('Access-Control-Allow-Origin: ' . $this->request->server['HTTP_ORIGIN']);
      $this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
      $this->response->addHeader('Access-Control-Max-Age: 1000');
      $this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
    }

    $this->response->addHeader('Content-Type: application/json');
    $this->response->setOutput(json_encode($json));
  }

  protected function form(){
        $data['breadcrumbs'] = array();

    $data['breadcrumbs'][] = array(
      'text' => $this->language->get('text_home'),
      'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
    );

    $data['breadcrumbs'][] = array(
      'text' => '库存查看',
      'href' => $this->url->link('sale/requisition_logcenter', 'token=' . $this->session->data['token'] , 'SSL')
    );

    $data['token'] = $this->session->data['token'];

    $id = I('get.requisition_id');
    if(!$id){
      $id=0;
    }
    

    if (isset($this->session->data['error'])) {
      $data['error_warning'] = $this->session->data['error'];

      unset($this->session->data['error']);
    } elseif (isset($this->error['warning'])) {
      $data['error_warning'] = $this->error['warning'];
    } else {
      $data['error_warning'] = '';
    }

    if (isset($this->session->data['success'])) {
      $data['success'] = $this->session->data['success'];

      unset($this->session->data['success']);
    } else {
      $data['success'] = '';
    }
    
    $requisition = $this->model_sale_check_stock->getRequisition($id);
    $data['requisition'] = $requisition;
    $po_products = $this->model_sale_check_stock->getRequisitionProducts($id);
    $data['requisition_products'] = $requisition_products;

    $data['header'] = $this->load->controller('common/header');
    $data['column_left'] = $this->load->controller('common/column_left');
    $data['footer'] = $this->load->controller('common/footer');

    $this->response->setOutput($this->load->view('sale/requisition_logcenter.tpl', $data));
  }

  

  protected function getList() {
    $this->document->addScript('view/javascript/floatthead/jquery.floatThead.min.js');

    $this->load->model('sale/lgi_order');
    $page = I('get.page');
    if(!$page){
      $page = 1;
    }
    if($this->user->getLp()){
      $where['requisition.src_logcenter'] = $this->user->getLp();
      $where['requisition.des_logcenter'] = $this->user->getLp();
      $where['_logic'] = 'or';
      $filter['_complex'] = $where;
    }

    else if($this->user->getVp()){
      $filter['requisition.vendor_id'] = $this->user->getId();
    }
    else{
      
    }
    $data = I('get.');

    if (isset($data['order'])) {
      $order = $data['order'];
    } else {
      $order = 'DESC';
    }

    $filter['order'] = $order;

    if(isset($data['filter_date_end'])){
      if($this->validateDate($data['filter_date_end'],'Y-m-d')){
        $filter_date_end = $data['filter_date_end'];
      }else{
        $filter_date_end = '9999-12-31';
      } 
    }else{
      $filter_date_end = '9999-12-31';
    }

    $filter['filter_date_end'] = $filter_date_end;

    if(isset($data['filter_vendor_name'])){
      $filter_vendor_name = trim($data['filter_vendor_name']);
    }else{
      $filter_vendor_name = '';
    }

    $filter['filter_vendor_name'] = $filter_vendor_name;

    if(!empty($data['filter_logcenter'])){
      $filter_logcenter = trim($data['filter_logcenter']);
    }else{
      $filter_logcenter = 4;
    }

    $filter['filter_logcenter'] = $filter_logcenter;

    if(isset($data['filter_date_start'])){

      if($this->validateDate($data['filter_date_start'],'Y-m-d')){
        $filter_date_start = $data['filter_date_start'];
      }else{
        $filter_date_start = $this->getStartTime($filter_logcenter);
      }   
    }else{
      $filter_date_start = $this->getStartTime($filter_logcenter);
    }

    $filter['filter_date_start'] = $filter_date_start;

    if(!empty($data['filter_sku'])){
      $filter_sku = trim($data['filter_sku']);
    }else{
      $filter_sku = '';
    }
    $filter['filter_sku'] = $filter_sku;
    if(!empty($data['sort'])){
      $sort = $data['sort'];
    }else{
      $sort = 'total_real_initiai';
    }

    $filter['sort'] = $sort;

    if(!empty($data['filter_model'])){
      $filter_model = trim($data['filter_model']);
    }else{
      $filter_model = '';
    }

    if($filter_model){
      $sku_by_model = $this->model_sale_check_stock->getSkuByModel($filter_model);
      if($sku_by_model){
        $filter['filter_sku'] = $sku_by_model;
      }
    }

    // if(!empty($data['filter_product_name'])){
    //   $filter_product_name = trim($data['filter_product_name']);
    // }else{
    //   $filter_product_name = '';
    // }

    // $filter['filter_product_name'] = $filter_product_name;

    $product_list =  $this->model_sale_check_stock->getList($page, $filter);

    $product_total = $this->model_sale_check_stock->getListCount($filter);

    $pagination = new Pagination();
    $pagination->total = $product_total;
    $pagination->page = $page;
    $pagination->limit = $this->config->get('config_limit_admin');
    $pagination->url = $this->url->link('sale/check_main_stock', 'token=' . $this->session->data['token'] . '&page={page}'.'&filter_date_end='.$data['filter_date_end'].'&filter_date_start='.$data['filter_date_start'].'&filter_logcenter='.$data['filter_logcenter'].'&filter_sku='.$data['filter_sku'].'&filter_product_name='.$data['filter_product_name'].'&filter_vendor_name='.$data['filter_vendor_name'].'&filter_model='.$data['filter_model'].'&sort='.$data['sort'].'&order='.$data['order'], 'SSL');

    $data['sort_initiai'] = $this->url->link('sale/check_main_stock', 'token=' . $this->session->data['token'] . '&page={page}'.'&filter_date_end='.$data['filter_date_end'].'&filter_date_start='.$data['filter_date_start'].'&filter_logcenter='.$data['filter_logcenter'].'&filter_sku='.$data['filter_sku'].'&filter_product_name='.$data['filter_product_name'].'&filter_vendor_name='.$data['filter_vendor_name'].'&filter_model='.$data['filter_model'].'&sort=total_real_initiai', 'SSL');

    $data['pagination'] = $pagination->render();

    $data['view_url'] = $this->url->link('sale/check_main_stock/view', 'token=' . $this->session->data['token'] . '&page={page}'.'&filter_date_end='.$data['filter_date_end'].'&filter_date_start='.$data['filter_date_start'].'&filter_logcenter='.$filter_logcenter.'&filter_product_name='.$data['filter_product_name'].'&filter_vendor_name='.$data['filter_vendor_name'], 'SSL');

    $data['export_url'] = $this->url->link('sale/check_main_stock/export', 'token=' . $this->session->data['token'] . '&page={page}'.'&filter_date_end='.$data['filter_date_end'].'&filter_date_start='.$data['filter_date_start'].'&filter_logcenter='.$filter_logcenter.'&filter_product_name='.$data['filter_product_name'].'&filter_vendor_name='.$data['filter_vendor_name'], 'SSL');

    $logcenters_list = $this->model_sale_lgi_order->getAllLogcenters();

    foreach ($logcenters_list as $key => $value) {
        $assing_logcenters_list[$value['logcenter_id']] = $value['logcenter_name'];
    } 

    if ($order == 'ASC') {
      $data['sort_initiai'] .= '&order=DESC';
    } else {
      $data['sort_initiai'] .= '&order=ASC';
    }

      $data['order'] = $order;
    $data['logcenters'] = $assing_logcenters_list;

    $data['breadcrumbs'] = array();

    $data['breadcrumbs'][] = array(
      'text' => $this->language->get('text_home'),
      'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
    );

    $data['breadcrumbs'][] = array(
      'text' => '库存查看',
      'href' => $this->url->link('sale/check_main_stock', 'token=' . $this->session->data['token'] , 'SSL')
    );

    if (isset($this->session->data['error'])) {
      $data['error_warning'] = $this->session->data['error'];

      unset($this->session->data['error']);
    } elseif (isset($this->error['warning'])) {
      $data['error_warning'] = $this->error['warning'];
    } else {
      $data['error_warning'] = '';
    }

    if (isset($this->session->data['success'])) {
      $data['success'] = $this->session->data['success'];

      unset($this->session->data['success']);
    } else {
      $data['success'] = '';
    }

    $data['token'] = $this->session->data['token'];
    
    $data['product_list'] = $product_list;

    $data['header'] = $this->load->controller('common/header');
    $data['column_left'] = $this->load->controller('common/column_left');
    $data['footer'] = $this->load->controller('common/footer');

    $this->response->setOutput($this->load->view('sale/check_stock_main_list.tpl', $data));
  }

  function validateDate($date, $format = 'Y-m-d H:i:s')
  {
      $d = DateTime::createFromFormat($format, $date);
      return $d && $d->format($format) == $date;
  }

  public function genVendorBill(){
    $vendor_bill_month = I('get.year_month');
    $month_valid = $this->validateDate($vendor_bill_month, 'Y-m');
    if(!$month_valid) {
      $this->session->data['error'] = '请选择有效的年月日期';
      $this->response->redirect($this->url->link('sale/order', 'token=' . $this->session->data['token'], 'SSL'));
    }
    //获取选择月份之前半年内所有还未对账的完成状态的订单
    $d = DateTime::createFromFormat('Y-m', $vendor_bill_month);
    $cur_year_month = $d->format('Y-m-01');
    $cur_month = $d->format('Y-m-21');
    $d->modify('-6 month');
    $end_month = $d->format('Y-m-d');
    $this->load->model('sale/vendor_bill');
    $this->load->model('sale/check_stock');
    $billed_po = $this->model_sale_vendor_bill->getBilledPo($cur_month, $end_month);
    $billed_po_ids = array();
    foreach ($billed_po as $bo) {
      $billed_po_ids[] = $bo['po_id'];
    }

    $vendor_ids = $this->model_sale_check_stock->getVendorIdsFromPo($cur_month, $end_month, $billed_po_ids);

    foreach ($vendor_ids as $vendor_id) {
      $bill_data = $this->model_sale_check_stock->getToBillPo($cur_month, $end_month, $billed_po_ids, $vendor_id['vendor_id']);  
      $bill_data_full[$vendor_id['vendor_id']] = $bill_data;
    }

    $commission = 1;
    foreach ($bill_data_full as $vendor_id=>$bill_data) {
      $po_total = 0;
      $po_ids = array();
      foreach ($bill_data as $po) {
        $po_total += (float)$po['total'];
        $po_ids[] = $po['id'];
      }
      $commission_total = $po_total*$commission;
      $data = array();

      //此处的$vendor_id是po表中的vendor_id 对应的是 vendors表中的user_id
      $this->load->model('catalog/vendor');
      $vendor_info = $this->model_catalog_vendor->getVendorByUserId($vendor_id);
      $data['vendor_id'] = $vendor_info['vendor_id'];
      $data['year_month'] = $cur_year_month;
      $data['total'] = $commission_total;
      $data['po_total'] = $po_total;
      $data['date_added'] = date('Y-m-d H:i:s', time());
      $vendor_bill_id = $this->model_sale_vendor_bill->saveVendorBill($data, $po_ids);

      //添加生成po操作记录
      $this->load->model('user/user');
      $user_info = $this->model_user_user->getUser($this->user->getId());
      $comment = '新增品牌商对账单';
      $this->model_sale_vendor_bill->addVendorBillHistory($vendor_bill_id, $this->user->getId(), $user_info['fullname'], $comment);      
    }
    


    $this->session->data['success'] = '生成品牌厂商对账单成功';
    $this->response->redirect($this->url->link('sale/vendor_bill', 'token=' . $this->session->data['token'], 'SSL'));
  }

    public function saveStock(){
    if ($this->request->server['REQUEST_METHOD'] == 'POST') {
      $this->load->model('sale/check_stock');
      $data = json_decode(file_get_contents('php://input'), true);
      $filter = C('DEFAULT_FILTER');
      $data   =   is_array($data) ? array_map_recursive($filter,$data) : $filter($data);
      
      if(!$data['products']){
        $this->response->setOutput(json_encode(array('error'=>'数据不完整')));
        return;
      }

      $to_save_stock = array();
      foreach ($data['products'] as $requisition_product) {
        $to_save_stock[$requisition_product['requisition_product_id']] = $requisition_product['stock'];
        $to_save_comment[$requisition_product['requisition_product_id']] = $requisition_product['comment'];
      }

      $to_save_stock2 = array();

      // $id = I('rost.ro_id');
      $id = $data['requisition_id'];
      if(!$id){
        $id=0;
      }
      $requisition = $this->model_sale_check_stock->getRequisition($id);
      //判断po状态，如果是已经结算或者已经关闭，则不允许修改po数量

      if($requisition['status'] != 2) {
        $this->response->setOutput(json_encode(array('error'=>'不能修改已结算和已关闭库存调整单')));
        return;
      }

      $requisition_products = $this->model_sale_check_stock->getRequisitionProducts($id);

      foreach ($requisition_products as $requisition_p) {
        if(isset($to_save_stock[$requisition_p['id']])) {
          $to_save_stock2[$requisition_p['id']] = $to_save_stock[$requisition_p['id']];
          $to_save_comment2[$requisition_p['id']] = $to_save_comment[$requisition_p['id']];
        }
        if(isset($to_save_comment[$requisition_p['id']])) {
          $to_save_comment2[$requisition_p['id']] = $to_save_comment[$requisition_p['id']];
        }
      }

      $this->model_sale_check_stock->setStock($id, $to_save_stock2);
      $this->model_sale_check_stock->setComment($id, $to_save_comment2);

      $this->response->setOutput(json_encode(array('success'=>'修改库存成功')));
      return;
    } 
  }

  public function forceCompletePo() {
    if ($this->request->server['REQUEST_METHOD'] == 'POST') {
      $this->load->model('sale/check_stock');
      $data = json_decode(file_get_contents('php://input'), true);
      $filter = C('DEFAULT_FILTER');
      $data   =   is_array($data) ? array_map_recursive($filter,$data) : $filter($data);
      // $id = I('post.po_id');
      $id = $data['po_id'];
      if(!$id){
        $id=0;
      }
      $po = $this->model_sale_check_stock->getPo($id);
      //判断po状态
      if($po['status'] != 3) {
        $this->response->setOutput(json_encode(array('error'=>'只能审核完成部分收货状态库存查看')));
        return;
      }

      if($po['status'] == 3) {
        //修改po单的total
        $po_products = $this->model_sale_check_stock->getRequisitionProducts($id);
        $new_total = 0;
        foreach ($po_products as $po_product) {
          $new_total += (float)$po_product['unit_price']*(float)$po_product['delivered_qty'];
        }
        $this->model_sale_check_stock->setPoTotal($id, $new_total);

        //修改po的status到审核完成
        $po_status = 6;
        $this->model_sale_check_stock->changePoStatus($id, $po_status);

        //添加po状态修改操作记录
        $this->load->model('user/user');
        $user_info = $this->model_user_user->getUser($this->user->getId());
        $comment = '审核完成库存查看。库存查看金额改为：' . $new_total . '￥';
        $this->model_sale_check_stock->addPoHistory($id, $this->user->getId(), $user_info['fullname'], $comment);  
      }

      $this->response->setOutput(json_encode(array('success'=>'修改库存查看状态成功')));
      return;
    } 
  }
  // public function exportLists(){
  //   $this->load->model('sale/check_stock');
  //   if($this->user->getLp()){
  //     $filter['po.user_id'] = $this->user->getId();
  //   }
  //   else if($this->user->getVp()){
  //     $filter['po.vendor_id'] = $this->user->getId();
  //   }

  //   $data = I('get.');

  //   if(isset($data['filter_date_start'])){
  //     $filter_date_start = $data['filter_date_start'];
  //   }else{
  //     $filter_date_start = $this->getStartTime($filter_logcenter);
  //   }

  //   if(isset($data['filter_date_end'])){
  //     $filter_date_end = $data['filter_date_end'];
  //   }else{
  //     $filter_date_end = '9999-12-31';
  //   }

  //   $filter['po.date_added'] = array('between',array($filter_date_start,$filter_date_end));
  //   $filter2 = $filter;
  //   if(isset($data['filter_vendor_name'])){
  //     $filter_vendor_name = trim($data['filter_vendor_name']);
  //     $filter['v.vendor_name'] = array('like',"%".$filter_vendor_name."%");
  //   }

  //   if(isset($data['filter_logcenter'])){
  //     $filter_logcenter = trim($data['filter_logcenter']);
  //     $filter['lg.logcenter_name'] = array('like',"%".$filter_logcenter."%");
  //   }

  //   if(isset($data['filter_status'])){
  //     $filter_status = trim($data['filter_status']);
  //     if($filter_status!='*'){
  //       $filter['po.status'] = $filter_status;
  //     }  
  //   }

  //   $po_list =  $this->model_sale_check_stock->getAllProductList($filter);

  //   $status_array = getPoStatus();
  //   foreach ($po_list as $key => $value) {
  //     $save_data[] = array(
  //       'name'          =>  $value['name'],
  //       'option_name'   =>  $value['option_name'],
  //       'qty'           =>  $value['qty'],
  //       'price'         =>  $value['price'],
  //       'unit_price'    =>  $value['unit_price'],
  //       'delivered_qty' =>  $value['delivered_qty'],
  //       'packing_no'    =>  $value['packing_no'],
  //       'id'            =>  $value['id'],
  //       'date_added'    =>  $value['date_added'],
  //       'total'         =>  $value['total'],
  //       'vendor_name'   =>  $value['vendor_name'],
  //       'logcenter_name'=>  $value['logcenter_name'],
  //       'count'         =>  $value['count'],
  //       'status'        =>  $status_array[$value['status']],
  //       );
  //   }

  //   $this->load->library('PHPExcel/PHPExcel');
  //   $objPHPExcel = new PHPExcel();    
  //   $objProps = $objPHPExcel->getProperties();    
  //   $objProps->setCreator("Think-tec");
  //   $objProps->setLastModifiedBy("Think-tec");    
  //   $objProps->setTitle("Think-tec Contact");    
  //   $objProps->setSubject("Think-tec Contact Data");    
  //   $objProps->setDescription("Think-tec Contact Data");    
  //   $objProps->setKeywords("Think-tec Contact");    
  //   $objProps->setCategory("Think-tec");
  //   $objPHPExcel->setActiveSheetIndex(0);     
  //   $objActSheet = $objPHPExcel->getActiveSheet(); 
       
  //   $objActSheet->setTitle('Sheet1');
  //   $col_idx = 'A';
  //   $headers = array( '编号','商品名称','选项', '单价','数量','总价','箱入数','已收货数量', '创建时间',   '采购金额',  '供应商', '物流中心',     '商品品种', '库存查看状态');
  //   $requisitionw_keys = array('id','name','option_name','unit_price','qty','price','packing_no','delivered_qty',   'date_added', 'total','vendor_name','logcenter_name',  'count', 'status');
  //   foreach ($headers as $header) {
  //     $objActSheet->setCellValue($col_idx++.'1', $header);  
  //   }
  //   //添加物流信息
  //   $i = 2;
  //   foreach ($save_data as $rlst) {
  //     $col_idx = 'A';
  //     foreach ($requisitionw_keys as $rk) {
  //       // $objActSheet->setCellValue($col_idx++.$i, $rlst[$rk]); 
  //       $objActSheet->setCellValueExplicit($col_idx++.$i, $rlst[$rk], PHPExcel_Cell_DataType::TYPE_STRING);
  //     }
  //     $i++;
  //   } 

  //   $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    
  //   ob_end_clean();
  //   // Redirect output to a client’s web browser (Excel2007)
  //   header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  //   header('Content-Disposition: attachment;filename="return_logcenter_order_'.date('Y-m-d',time()).'.xlsx"');
  //   header('Cache-Control: max-age=0');
  //   // If you're serving to IE 9, then the following may be needed
  //   header('Cache-Control: max-age=1');

  //   // If you're serving to IE over SSL, then the following may be needed
  //   header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
  //   header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
  //   header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
  //   header ('Pragma: public'); // HTTP/1.0
  //   $objWriter->save('php://output'); 
  //   exit;
  // }
  public function export(){
    $this->load->model('sale/return_order');
    $this->load->model('sale/trim_stock');
    $this->load->model('sale/requisition');
    $this->load->model('sale/order');
    $this->load->model('sale/purchase_order');
    $sku = I('get.sku','');
    $filter_date_start = I('get.filter_date_start','2016-11-18 00:00:00');
    $filter_date_end = I('get.filter_date_end','9999-12-31 23:59:59');
    $filter_logcenter = I('get.filter_logcenter','4');
    $filter = array(
      'sku'               =>$sku,
      'filter_date_start' =>$filter_date_start?$filter_date_start:'2016-11-18 00:00:00',
      'filter_date_end'   =>$filter_date_end?$filter_date_end:'9999-12-31 23:59:59',
      'filter_logcenter'  =>$filter_logcenter?$filter_logcenter:4,
      );

    $ro_operation_data = $this->model_sale_return_order->getRoOperationBySku($filter);

    $trim_operation_data = $this->model_sale_trim_stock->getTrimOperationBySku($filter);
    $src_requisition_operation_data = $this->model_sale_requisition->getSrcRequisitionOperationBySku($filter);
    $des_requisition_operation_data = $this->model_sale_requisition->getDesRequisitionOperationBySku($filter);
    $order_operation_data = $this->model_sale_order->getOrderOperationBySku($filter);
    $po_operation_data = $this->model_sale_purchase_order->getPoOperationBySku($filter);
    

    $this->load->library('PHPExcel/PHPExcel');
    $objPHPExcel = new PHPExcel();    
    $objProps = $objPHPExcel->getProperties();    
    $objProps->setCreator("Think-tec");
    $objProps->setLastModifiedBy("Think-tec");    
    $objProps->setTitle("Think-tec Contact");    
    $objProps->setSubject("Think-tec Contact Data");    
    $objProps->setDescription("Think-tec Contact Data");    
    $objProps->setKeywords("Think-tec Contact");    
    $objProps->setCategory("Think-tec");
    //导出退货信息
    $objPHPExcel->setActiveSheetIndex(0);     
    $objActSheet = $objPHPExcel->getActiveSheet(); 
       
    $objActSheet->setTitle('退货单');
    $col_idx = 'A';
    $headers = array('商品名称','选项', '单价','箱入数','时间');
    $requisitionw_keys = array('name','option_name','unit_price','qty','deliver_time');
    foreach ($headers as $header) {
      $objActSheet->setCellValue($col_idx++.'1', $header);  
    }
    //添加物流信息
    $i = 2;
    foreach ($ro_operation_data as $rlst) {
      $col_idx = 'A';
      foreach ($requisitionw_keys as $rk) {
        // $objActSheet->setCellValue($col_idx++.$i, $rlst[$rk]); 
        $objActSheet->setCellValueExplicit($col_idx++.$i, $rlst[$rk], PHPExcel_Cell_DataType::TYPE_STRING);
      }
      $i++;
    } 
    //导出调整信息
    $requisition_sheet = new PHPExcel_Worksheet($objPHPExcel, '调整单');
    $objPHPExcel->addSheet($requisition_sheet);
    $objPHPExcel->setActiveSheetIndex(1);
    $objActSheet = $objPHPExcel->getActiveSheet(); 
    $col_idx = 'A';
    $headers = array('商品名称','选项', '单价','箱入数','时间');
    $requisitionw_keys = array('name','option_name','unit_price','qty','deliver_time');
    foreach ($headers as $header) {
      $objActSheet->setCellValue($col_idx++.'1', $header);  
    }
    //添加物流信息
    $i = 2;
    foreach ($trim_operation_data as $rlst) {
      $col_idx = 'A';
      foreach ($requisitionw_keys as $rk) {
        // $objActSheet->setCellValue($col_idx++.$i, $rlst[$rk]); 
        $objActSheet->setCellValueExplicit($col_idx++.$i, $rlst[$rk], PHPExcel_Cell_DataType::TYPE_STRING);
      }
      $i++;
    }

    //导出采购
    $po_sheet = new PHPExcel_Worksheet($objPHPExcel, '采购单');
    $objPHPExcel->addSheet($po_sheet);
    $objPHPExcel->setActiveSheetIndex(2);
    $objActSheet = $objPHPExcel->getActiveSheet(); 
    $col_idx = 'A';
    $headers = array('商品名称','选项', '单价','箱入数','时间');
    $requisitionw_keys = array('name','option_name','unit_price','qty','deliver_time');
    foreach ($headers as $header) {
      $objActSheet->setCellValue($col_idx++.'1', $header);  
    }
    //添加物流信息
    $i = 2;
    foreach ($po_operation_data as $rlst) {
      $col_idx = 'A';
      foreach ($requisitionw_keys as $rk) {
        // $objActSheet->setCellValue($col_idx++.$i, $rlst[$rk]); 
        $objActSheet->setCellValueExplicit($col_idx++.$i, $rlst[$rk], PHPExcel_Cell_DataType::TYPE_STRING);
      }
      $i++;
    }

    //导出销售
    $order_sheet = new PHPExcel_Worksheet($objPHPExcel, '销售单');
    $objPHPExcel->addSheet($order_sheet);
    $objPHPExcel->setActiveSheetIndex(3);
    $objActSheet = $objPHPExcel->getActiveSheet(); 
    $col_idx = 'A';
    $headers = array('商品名称','选项', '单价','箱入数','时间');
    $requisitionw_keys = array('name','option_name','unit_price','qty','deliver_time');
    foreach ($headers as $header) {
      $objActSheet->setCellValue($col_idx++.'1', $header);  
    }
    //添加物流信息
    $i = 2;
    foreach ($order_operation_data as $rlst) {
      $col_idx = 'A';
      foreach ($requisitionw_keys as $rk) {
        // $objActSheet->setCellValue($col_idx++.$i, $rlst[$rk]); 
        $objActSheet->setCellValueExplicit($col_idx++.$i, $rlst[$rk], PHPExcel_Cell_DataType::TYPE_STRING);
      }
      $i++;
    }

    //导出调进
    $des_requisition_sheet = new PHPExcel_Worksheet($objPHPExcel, '调拨单调进');
    $objPHPExcel->addSheet($des_requisition_sheet);
    $objPHPExcel->setActiveSheetIndex(4);
    $objActSheet = $objPHPExcel->getActiveSheet(); 
    $col_idx = 'A';
    $headers = array('商品名称','选项', '单价','箱入数','时间');
    $requisitionw_keys = array('name','option_name','unit_price','qty','deliver_time');
    foreach ($headers as $header) {
      $objActSheet->setCellValue($col_idx++.'1', $header);  
    }
    //添加物流信息
    $i = 2;
    foreach ($des_requisition_operation_data as $rlst) {
      $col_idx = 'A';
      foreach ($requisitionw_keys as $rk) {
        // $objActSheet->setCellValue($col_idx++.$i, $rlst[$rk]); 
        $objActSheet->setCellValueExplicit($col_idx++.$i, $rlst[$rk], PHPExcel_Cell_DataType::TYPE_STRING);
      }
      $i++;
    }

    //导出调出
    $src_requisition_sheet = new PHPExcel_Worksheet($objPHPExcel, '调拨单调出');
    $objPHPExcel->addSheet($src_requisition_sheet);
    $objPHPExcel->setActiveSheetIndex(5);
    $objActSheet = $objPHPExcel->getActiveSheet(); 
    $col_idx = 'A';
    $headers = array('商品名称','选项', '单价','箱入数','时间');
    $requisitionw_keys = array('name','option_name','unit_price','qty','deliver_time');
    foreach ($headers as $header) {
      $objActSheet->setCellValue($col_idx++.'1', $header);  
    }
    //添加物流信息
    $i = 2;
    foreach ($src_requisition_operation_data as $rlst) {
      $col_idx = 'A';
      foreach ($requisitionw_keys as $rk) {
        // $objActSheet->setCellValue($col_idx++.$i, $rlst[$rk]); 
        $objActSheet->setCellValueExplicit($col_idx++.$i, $rlst[$rk], PHPExcel_Cell_DataType::TYPE_STRING);
      }
      $i++;
    }

    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    
    ob_end_clean();
    // Redirect output to a client’s web browser (Excel2007)
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="check_main_stock'.date('Y-m-d',time()).'.xlsx"');
    header('Cache-Control: max-age=0');
    // If you're serving to IE 9, then the following may be needed
    header('Cache-Control: max-age=1');

    // If you're serving to IE over SSL, then the following may be needed
    header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
    header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
    header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
    header ('Pragma: public'); // HTTP/1.0
    $objWriter->save('php://output'); 
    exit;
  }

  public function exportTpl(){
    $filter_data['pd.name'] = array('like','%'.$filter_name.'%');
    $this->load->model('catalog/mvd_product');
    $allProduct_data = $this->model_catalog_mvd_product->getAllProductsDetail($filter_data);
    foreach ($allProduct_data as $key => $value) {
      $save_data[$key] = array(
        'product_id'  => $value['product_id'],
        'name'          => $value['name'],
        'ovd_name'      => $value['ovd_name'],
        'option_value_id'=>$value['option_value_id'],
        'sku'=>$value['sku'],
        );
    }
    $this->load->library('PHPExcel/PHPExcel');
    $objPHPExcel = new PHPExcel();    
    $objProps = $objPHPExcel->getProperties();    
    $objProps->setCreator("Think-tec");
    $objProps->setLastModifiedBy("Think-tec");    
    $objProps->setTitle("Think-tec Contact");    
    $objProps->setSubject("Think-tec Contact Data");    
    $objProps->setDescription("Think-tec Contact Data");    
    $objProps->setKeywords("Think-tec Contact");    
    $objProps->setCategory("Think-tec");
    $objPHPExcel->setActiveSheetIndex(0);     
    $objActSheet = $objPHPExcel->getActiveSheet(); 
       
    $objActSheet->setTitle('Sheet1');
    $col_idx = 'A';
    $headers = array('条码','商品名称','选项','商品ID','选项ID','实时库存');
    $row_keys = array('sku','name', 'ovd_name', 'product_id','option_value_id');
    foreach ($headers as $header) {
      $objActSheet->setCellValue($col_idx++.'1', $header);  
    }
    //添加物流信息
    $i = 2;
    foreach ($save_data as $rlst) {
      $col_idx = 'A';
      foreach ($row_keys as $rk) {
        // $objActSheet->setCellValue($col_idx++.$i, $rlst[$rk]); 
        $objActSheet->setCellValueExplicit($col_idx++.$i, $rlst[$rk], PHPExcel_Cell_DataType::TYPE_STRING);
      }
      $i++;
    } 
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    ob_end_clean();
    // Redirect output to a client’s web browser (Excel2007)
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="check_stock_'.date('Y-m-d',time()).'.xlsx"');
    header('Cache-Control: max-age=0');
    // If you're serving to IE 9, then the following may be needed
    header('Cache-Control: max-age=1');

    // If you're serving to IE over SSL, then the following may be needed
    header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
    header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
    header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
    header ('Pragma: public'); // HTTP/1.0
     
    $objWriter->save('php://output'); 

    exit;
  }

  public function import() {
    $json = array();
    if (1) {
      if (!empty($this->request->files['file']['name']) && is_file($this->request->files['file']['tmp_name'])) {
        // Sanitize the filename
        $filename = basename(html_entity_decode($this->request->files['file']['name'], ENT_QUOTES, 'UTF-8'));
        // Validate the filename length
        if ((utf8_strlen($filename) < 3) || (utf8_strlen($filename) > 128)) {
          $json['error'] = '文件名过短';
        }
        // Allowed file extension types
        $allowed = array('xls','xlsx');
        if (!in_array(strtolower(substr(strrchr($filename, '.'), 1)), $allowed)) {
          $json['error'] = '请上传xls或者xlsx文件';
        }
        // Return any upload error
        if ($this->request->files['file']['error'] != UPLOAD_ERR_OK) {
          $json['error'] = '上传出现错误';
        }
      } 
    }
    else {
      $json['error'] = '上传失败';
    }

    if (!$json) {
      $this->load->library('PHPExcel/PHPExcel');
      $savePath = $this->request->files['file']['tmp_name'];
      $PHPExcel = new PHPExcel();
      $PHPReader = new PHPExcel_Reader_Excel2007();
      if(!$PHPReader->canRead($savePath)){
        $PHPReader = new PHPExcel_Reader_Excel5();
      }
      $PHPExcel = $PHPReader->load($savePath);
      $currentSheet = $PHPExcel->getSheet(0);
      $allRow = $currentSheet->getHighestRow();
      //获取order_product_id, express_name, express_number在excel中的index
      $initiai_idx = $option_id_idx = $name_idx = $option_idx = $product_id_idx = 0;
      $tmp_idx = 'A'; //假设导入表格不会长于Z
      $currentRow = 1;
      while(($name_idx === 0 || $option_idx === 0 || $product_id_idx === 0 || $option_id_idx === 0 || $initiai_idx=== 0)&&$tmp_idx<'Z') {
        switch (trim((String)$currentSheet->getCell($tmp_idx.$currentRow)->getValue())) {
          case '商品名称':
            $name_idx = $tmp_idx;
            break;
          case '选项':
            $option_idx = $tmp_idx;
            break;
          case '商品ID':
            $product_id_idx = $tmp_idx;
            break;
          case '选项ID':
            $option_id_idx = $tmp_idx;
            break;
          case '实时库存':
            $initiai_idx = $tmp_idx;
            break;
        }
        $tmp_idx++;
      }
      
      if(0 === $initiai_idx || 0 === $option_idx||0 === $name_idx||0===$product_id_idx||0===$option_id_idx) {
        $json['error'] = '请检查文件第一行是否有：条码、选项名、数量';
      }
      
      if (!$json) {
        $products_info = array();
        for ($currentRow = 2;$currentRow <= $allRow;$currentRow++) {
          $name = (String)$currentSheet->getCell($name_idx.$currentRow)->getValue();
          $option_name = (String)$currentSheet->getCell($option_idx.$currentRow)->getValue();
          $product_id = (String)$currentSheet->getCell($product_id_idx.$currentRow)->getValue();
          $initiai = (String)$currentSheet->getCell($initiai_idx.$currentRow)->getValue();
          $option_id = (String)$currentSheet->getCell($option_id_idx.$currentRow)->getValue();
          if($initiai){
            $product_data['product_id'] = $product_id;
            $product_option_model = M('product_option_value');
            $product_option_map = array(
              'product_id' => $product_id,
              'option_value_id'=> $option_id,
              );
            $product_option_id = $product_option_model->where($product_option_map)->getField('product_option_value_id');
            $product_data['option_id'] = $product_option_id?$product_option_id:-1;
            $product_data['date_added'] = date('Y-m-d h:i:s',time());
            $product_data['logcenter_id'] = 4;
            $product_data['initial_number'] = $initiai;


            $products_info[] = $product_data;
          }
          
        }        

        
      }
      $model = M('product_initiai');
      foreach ($products_info as $key => $value) {
          $model->data($value)->add();
      }

      if (!isset($json['error'])) {
        $json['success'] = sprintf('更新新建退货单 %s条商品记录', count($products_info));
      }
    }

    $this->response->addHeader('Content-Type: application/json');
    $this->response->setOutput(json_encode($json));

  }

  public function exportAllList(){
    $this->load->model('sale/check_stock');
    $data = I('get.');

    

    if(isset($data['filter_date_end'])){
      if($this->validateDate($data['filter_date_end'],'Y-m-d')){
        $filter_date_end = $data['filter_date_end'];
      }else{
        $filter_date_end = '9999-12-31';
      } 
    }else{
      $filter_date_end = '9999-12-31';
    }

    $filter['filter_date_end'] = $filter_date_end;

    if(isset($data['filter_vendor_name'])){
      $filter_vendor_name = trim($data['filter_vendor_name']);
    }else{
      $filter_vendor_name = '';
    }

    $filter['filter_vendor_name'] = $filter_vendor_name;

    if(!empty($data['filter_logcenter'])){
      $filter_logcenter = trim($data['filter_logcenter']);
    }else{
      $filter_logcenter = 4;
    }

    if(isset($data['filter_date_start'])){

      if($this->validateDate($data['filter_date_start'],'Y-m-d')){
        $filter_date_start = $data['filter_date_start'];
      }else{
        $filter_date_start = $this->getStartTime($filter_logcenter);
      }   
    }else{
      $filter_date_start = $this->getStartTime($filter_logcenter);
    }

    $filter['filter_date_start'] = $filter_date_start;

    $filter['filter_logcenter'] = $filter_logcenter;

    if(!empty($data['filter_sku'])){
      $filter_sku = trim($data['filter_sku']);
    }else{
      $filter_sku = '';
    }

    $filter['filter_sku'] = $filter_sku;

    if(!empty($data['filter_model'])){
      $filter_model = trim($data['filter_model']);
    }else{
      $filter_model = '';
    }

    if($filter_model){
      $sku_by_model = $this->model_sale_check_stock->getSkuByModel($filter_model);
      if($sku_by_model){
        $filter['filter_sku'] = $sku_by_model;
      }
    }
    
    $product_list =  $this->model_sale_check_stock->getAllListProductsOption($filter);

    $this->load->library('PHPExcel/PHPExcel');
    $objPHPExcel = new PHPExcel();    
    $objProps = $objPHPExcel->getProperties();    
    $objProps->setCreator("Think-tec");
    $objProps->setLastModifiedBy("Think-tec");    
    $objProps->setTitle("Think-tec Contact");    
    $objProps->setSubject("Think-tec Contact Data");    
    $objProps->setDescription("Think-tec Contact Data");    
    $objProps->setKeywords("Think-tec Contact");    
    $objProps->setCategory("Think-tec");
    $objPHPExcel->setActiveSheetIndex(0);     
    $objActSheet = $objPHPExcel->getActiveSheet(); 
       
    $objActSheet->setTitle('Sheet1');
    $col_idx = 'A';
    $headers = array('商品名称','选项','价格','建议售价','零售价','SKU','期初数','订单数量','采购单数量','退货单数量','调整单数量','调进数量','调出数量','变动数量','库存数量');
    $row_keys = array('name','option_name', 'product_cost','price','special', 'sku','initiai','order','po','ro','trim','des_requisition','src_requisition','change','last');
    foreach ($headers as $header) {
      $objActSheet->setCellValue($col_idx++.'1', $header);  
    }
    //添加物流信息
    $i = 2;
    foreach ($product_list as $rlst) {
      $col_idx = 'A';
      foreach ($row_keys as $rk) {
        // $objActSheet->setCellValue($col_idx++.$i, $rlst[$rk]); 
        $objActSheet->setCellValueExplicit($col_idx++.$i, $rlst[$rk], PHPExcel_Cell_DataType::TYPE_STRING);
      }
      $i++;
    } 
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    ob_end_clean();
    // Redirect output to a client’s web browser (Excel2007)
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="check_stock_'.date('Y-m-d',time()).'.xlsx"');
    header('Cache-Control: max-age=0');
    // If you're serving to IE 9, then the following may be needed
    header('Cache-Control: max-age=1');

    // If you're serving to IE over SSL, then the following may be needed
    header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
    header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
    header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
    header ('Pragma: public'); // HTTP/1.0
     
    $objWriter->save('php://output'); 

    exit;
  }

  public function getStartTime($filter_logcenter){
    $filter_time_array = getLogcenterInitiaiTime();

    $filter_time = $filter_time_array[$filter_logcenter];
    $filter_time = $filter_time?$filter_time:'2016-11-18';
    return $filter_time;
  }

  public function updateInitiai(){
    $logcenter_date = getLogcenterInitiaiTime();
    $this->load->model('sale/check_stock');
    $filter_date_end = '9999-12-31';
    $filter['filter_date_end'] = $filter_date_end;

    $filter_sku = '';
    $filter['filter_sku'] = $filter_sku;

    $filter['filter_vendor_name'] = '';
    foreach ($logcenter_date as $key => $value) {
        $filter['filter_logcenter'] = $key;
        $filter['filter_date_start'] = $value;
        $product_list =  $this->model_sale_check_stock->getAllListProductsOption($filter);
        $this->saveInitiai($product_list,$key);
    }

  }

  public function saveInitiai($data,$logcenter_id){
    $product_initiai = M('product_initiai');
    foreach ($data as $key => $value) {
      $map = array(
        'product_id'  => $value['product_id'],
        'option_id'   => $value['product_option_value_id']?$value['product_option_value_id']:-1,
        'logcenter_id'=> $logcenter_id,
        );
      $product_initiai_data = $product_initiai
      ->where($map)
      ->find();
      //var_dump($value);die();
      if($product_initiai_data){
        $product_initiai_data['real_initiai'] = $value['last'];
        $product_initiai->data($product_initiai_data)->save();
      }else{
        $data = array(
          'product_id'  => $value['product_id'],
          'option_id'   => $value['product_option_value_id']?$value['product_option_value_id']:-1,
          'logcenter_id'=> $logcenter_id,
          'initiai_number'=> 0,
          'real_initiai'=> $value['last'],
          'date_added'  => date('Y-m-d h:i:s',time()),
          );
        $product_initiai->data($data)->add();
      }
    }
  }
}